//
//  GDCarPlateInputAccessoryView.m
//  CarPlateInputViewDemo
//
//  Created by ilongge on 2020/10/22.
//

#import "GDCarPlateInputAccessoryView.h"
#import "GDCarPlateInputAccessoryViewCell.h"

@interface GDCarPlateInputAccessoryView()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>

@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, strong) UIButton *specialButton;
@property (nonatomic, strong) UICollectionView *inputCollection;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, assign) CGSize titleSize;
@property (nonatomic, assign) CGFloat interitemSpacing;
@property (nonatomic, assign) NSInteger currentSelectIndex;
@property (nonatomic, assign) NSInteger lastSelectIndex;

@end

@implementation GDCarPlateInputAccessoryView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self parperData];
        [self initSubviews];
    }
    return self;
}


- (void)initSubviews
{
    
    self.backgroundColor = ColorFromHex(0xF5F5F5, 1);
    
    [self addSubview:self.cancelButton];
    [self addSubview:self.doneButton];
    [self addSubview:self.specialButton];
    
    [self configCollectionView];
    
    [self addSubview:self.inputCollection];
    
    [self.inputCollection reloadData];
}

- (void)parperData
{
    self.currentSelectIndex = 0;
    [self.titleArray removeAllObjects];
    [self.titleArray addObjectsFromArray:@[@"",@"",@"",@"",@"",@"",@"",@""]];
}

- (void)setCarPlate:(NSString *)carPlate{
    _carPlate = carPlate;
    for (NSInteger index = 0; index <carPlate.length; index++) {
        self.titleArray[index] = [carPlate substringWithRange:NSMakeRange(index, 1)];
    }
    [self.inputCollection reloadData];
    [self movePointToIndex:carPlate.length];
}

-(void)cancelButtonAction
{
    if (self.cancelButtonBlock) {
        self.cancelButtonBlock();
    }
    [self.window endEditing:YES];
}

-(void)doneButtonAction
{
    if (self.doneButtonBlock) {
        self.doneButtonBlock([self.titleArray componentsJoinedByString:@""]);
    }
}

-(void)specialButtonAction
{
    if (self.specialButtonBlock) {
        self.specialButtonBlock();
    }
}

- (void)insertCode:(NSString *)code
{
    self.titleArray[self.currentSelectIndex] = code;
    [self movePointToNext];
}

-(void)backSpaceAction
{
    NSString *code = self.titleArray[self.currentSelectIndex];
    if (code.length) {
        self.titleArray[self.currentSelectIndex] = @"";
        [self movePointToIndex:self.currentSelectIndex];
    }
    else{
        if (self.currentSelectIndex-1 < 0) {
            self.currentSelectIndex = 1;
        }
        self.titleArray[self.currentSelectIndex-1] = @"";
        [self movePointToLast];
    }
}


- (void)movePointToNext
{
    if (self.currentSelectIndex >= self.titleArray.count-1) {
        self.currentSelectIndex = self.titleArray.count-2;
    }
    [self movePointToIndex:self.currentSelectIndex+1];
}

- (void)movePointToLast
{
    if (self.currentSelectIndex-1 < 0) {
        self.currentSelectIndex = 1;
    }
    [self movePointToIndex:self.currentSelectIndex-1];
}

- (void)movePointToIndex:(NSInteger)index
{
    self.lastSelectIndex = self.currentSelectIndex;
    if (index == self.currentSelectIndex) {
        [UIView performWithoutAnimation:^{
            NSIndexPath *currentIndex = [NSIndexPath indexPathForRow:self.currentSelectIndex inSection:0];
            [self.inputCollection reloadItemsAtIndexPaths:@[currentIndex]];
        }];
    }
    else{
        self.currentSelectIndex = index;
        [UIView performWithoutAnimation:^{
            NSIndexPath *currentIndex = [NSIndexPath indexPathForRow:self.currentSelectIndex inSection:0];
            NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.lastSelectIndex inSection:0];
            [self.inputCollection reloadItemsAtIndexPaths:@[currentIndex,lastIndex]];
        }];
    }
    
    if (self.currentSelectIndexBlock) {
        self.currentSelectIndexBlock(self.currentSelectIndex);
    }
    
}

#pragma mark ************** layout
-(void)layoutSubviews
{
    CGFloat margin = 15;
    CGFloat width = self.frame.size.width;
    self.cancelButton.frame = CGRectMake(0, 0, 50, 40);
    self.doneButton.frame = CGRectMake(width - 50, 0, 50, 40);
    self.specialButton.frame = CGRectMake((width - 120) / 2.0, 8, 120, 20);
    self.inputCollection.frame = CGRectMake(margin, 50, width - margin * 2 , 42);
}

#pragma mark UICollectionViewDelegate / UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GDCarPlateInputAccessoryViewCell *cell = [GDCarPlateInputAccessoryViewCell carPlateInputAccessoryViewCell:collectionView
                                                                                                 forIndexPath:indexPath];
    NSString *titile = self.titleArray[indexPath.row];
    if (indexPath.row == 7
        &&
        titile.length == 0) {
        titile = NewEnergyResources;
    }
    if (self.currentSelectIndex == indexPath.row) {
        [cell configText:titile andActive:YES];
    }
    else{
        [cell configText:titile andActive:NO];
    }
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self movePointToIndex:indexPath.row];
}


- (void)configCollectionView
{
    self.titleSize = CGSizeMake(32, 40);
    self.interitemSpacing = (self.frame.size.width - 8 * 32 - 15 * 2) / 8;
    [self.inputCollection registerNib:[UINib nibWithNibName:[[GDCarPlateInputAccessoryViewCell class] description]
                                                     bundle:nil]
           forCellWithReuseIdentifier:[[GDCarPlateInputAccessoryViewCell class] description]];
}

#pragma mark **************懒加载

- (UICollectionView *)inputCollection
{
    if (_inputCollection == nil) {
        UICollectionViewFlowLayout *collectionLayOut = [[UICollectionViewFlowLayout alloc] init];
        collectionLayOut.minimumInteritemSpacing = self.interitemSpacing;
        collectionLayOut.itemSize = self.titleSize;
        _inputCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,0,0)
                                              collectionViewLayout:collectionLayOut];
        _inputCollection.delegate = self;
        _inputCollection.dataSource = self;
        _inputCollection.backgroundColor = [UIColor clearColor];
    }
    return _inputCollection;
}

- (NSMutableArray *)titleArray
{
    if (_titleArray == nil) {
        _titleArray = [[NSMutableArray alloc] init];
    }
    return _titleArray;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_cancelButton setTitleColor:ColorFromHex(0x666666, 1) forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)doneButton
{
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_doneButton setTitleColor:ColorFromHex(0x333333 , 1) forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneButton;
}

- (UIButton *)specialButton
{
    if (!_specialButton) {
        _specialButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_specialButton setTitle:@"特殊号牌，点击此处" forState:UIControlStateNormal];
        _specialButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_specialButton setTitleColor:ColorFromHex(0x335CD9, 1) forState:UIControlStateNormal];
        [_specialButton addTarget:self action:@selector(specialButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _specialButton;
}

@end
